from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer, BadData
from rest_framework_jwt.settings import api_settings


def generate_save_user_token(openid):
    """定义一个函数对用户openid进行加密
    ：:param openid:原始openid
    :return:加密后的openid
    """
    # 1 创建加载的序列化器对象
    serializer = TJSSerializer(secret_key=settings.SECRET_KEY,expires_in=600)
    # 1.1 把要加密的数据包装成字典
    data = {'openid':openid}

    # 2调用dumps 方法进行把对数据加密 注意应该把数据包装成 字典格式 加载完返回的数据类型是bytes
    openid_sign_bytes = serializer.dumps(data)

    # 3.把bytes转换成str返回
    return openid_sign_bytes.decode()


def check_save_user_token(openid_sign):
    """
    对加密后的openid 进行解密
    :param openid_sign:  加密后的openid
    :return: 加密成功返回openid 失败返回None
    """
    # 1.创建加载的序列化器对象
    serializer = TJSSerializer(secret_key=settings.SECRET_KEY, expires_in=600)
    # 2.调用loads方法进行对数据解密
    try:
        data = serializer.loads(openid_sign)  # 解密后它还是一个字典
    except BadData:  # 如果解密失败会抛出BadData的异常
        return None
    else:
        return data.get('openid')

def generate_token(user):
    """
    传user对象进行生成token
    :param user: 要生成JWT的用户
    :return: JWT token
    """
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载生成载荷函数
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token的函数

    payload = jwt_payload_handler(user)  # 通过传入user对象生成jwt 载荷部分
    token = jwt_encode_handler(payload)  # 传入payload 生成token

    return token

